import path from "path";
import { ICreateServiceParams } from "./createServices";
import { checkDirExists, createDirectory, writeToFile } from "../../utils/tools";

export function generCode(params: ICreateServiceParams) {
  const serName = `${params.moduleName}Service`;

  const tem = `
import express from "express";
import { formatRequestQuery, formatResponse } from "../../utils/tools";
import { ${serName} } from "../../services/${params.superDir}/${serName}";
import { uploadMiddleware } from "../middlewares/uploadFile";
const router = express.Router();
const queryField = [${params.fields?.map((item) => '"' + item + '"')}]

router.post("/", async (req, res) => {
  await ${serName}.add(req.body);
  res.send(formatResponse<null>(null, "操作成功"));
});

router.delete("/:id", async (req, res) => {
  const result = await ${serName}.delete(req.params.id);
  res.send(formatResponse(result));
});

router.put("/", async (req, res) => {
  const result = await ${serName}.update(req.body);
  res.send(formatResponse(result));
});

router.get("/page", async (req, res) => {
  const { query, other } = formatRequestQuery(req.query, queryField);
  const result = await ${serName}.findByPage(query.current, query.size, other);
  res.send(formatResponse<typeof result>(result));
});

router.get("/list", async (req, res) => {
  const { other } = formatRequestQuery(req.query, queryField);
  const result = await ${serName}.findByList(other);
  res.send(formatResponse<typeof result>(result));
});

router.get("/treeList", async (req, res) => {
  const { other } = formatRequestQuery(req.query, queryField);
  const result = await ${serName}.findByTreeList(other);
  res.send(formatResponse<typeof result>(result));
});

router.get("/:id", async (req, res) => {
  const result = await ${serName}.findById(req.params.id);
  res.send(formatResponse(result));
});

router.post("/import", uploadMiddleware().single("file"), async (req: any, res) => {
  const resp = await ${serName}.importData(req.file.path);

  res.send(formatResponse(\`成功导入 \${resp} 条数据\`));});

export default router;`;

  return tem;
}

export async function createRouter(params: ICreateServiceParams) {
  const codeText = generCode(params);
  const filename = params.moduleName + "Router.ts";

  // 1. 存放router的目录
  const dirPath = path.resolve(__dirname, "../../routes", params.superDir);
  if (!(await checkDirExists(dirPath))) {
    await createDirectory(dirPath);
  }

  // 2. 生成router文件
  const target = path.resolve(dirPath, filename);
  await writeToFile(target, codeText);
}
